import requests


# 需求：
# 提取其中的请求的要素，发送请求，获得响应

class RequestSend:
    # 发送请求--- 4要素
    def api_run(self, url, method, headers=None, data=None):
        response = None
        # 加一个判断，判断headers 里边 content-type 是不是json
        if headers['Content-Type'] == 'application/json':
            # 是json 格式， 就用json 参数来接受 数据
            response = requests.request(method=method, url=url, headers=headers, json=data)
        else:
            response = requests.request(method=method, url=url, headers=headers, data=data)
        # 收集响应的内容：
        # 状态码：
        code = response.status_code
        # 响应头
        res_headers = response.headers
        # 响应体
        try:
            body = response.json()
        except:
            body = {'nobody': '没数据'}

        # 最后是要将 response 的内容，集中在 像这个字典里边：
        # {‘状态码': 200, '响应头': ''， ’响应体‘： ’信息‘}
        # 设置一个空字典，用来接收这些内容
        dict1 = {}

        dict1['code'] = code
        dict1['headers'] = res_headers
        dict1['body'] = body

        return dict1

    def send(self, url, method, **kwargs):
        return self.api_run(url=url, method=method, **kwargs)


# 测试代码
if __name__ == '__main__':
    url = "http://127.0.0.1:6088/api/User"
    # data = {"username":"admin","password":"123"}
    data = None
    # method = "post"
    method = "get"
    # headers = {"Content-Type": "application/json"}
    headers = {"Content-Type": "application/x-www-form-urlencoded",
               'Authorization': 'eyJhY2NvdW50IjoiYWRtaW4iLCJ0b2tlbiI6IjliMmYyNWEzODkyZDY0OTlhMWYwZjMxMWJmZTgwMjhiIn0='}

    print(str(RequestSend().send(url=url, method=method, headers=headers, data=data)))
